﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;
using Report.BrowserFix;
using Report.Entity;
using Report.Service;

namespace Report.Engine
{
    public class ImageStep : IExportStep
    {
        private readonly Step step;

        public ImageStep(Step step)
        {
            this.step = step;
        }

        public virtual ExecuteResult Execute(ExportContext context)
        {
            string imageName = SaveChartImage(context);

            WordProcessor wordProcessor = context.WordProcessor;

            wordProcessor.ReplaceImage(step.BookMarkName, imageName);

            return ExecuteResult.NextStep;
        }

        public string SaveChartImage(ExportContext context)
        {
            var dm = new DomSelector(context.Document);

            var bitmaps = new List<Bitmap>();

            HTMLDocumentAccessor accessor = new HTMLDocumentAccessor(context.Document);

            foreach (string expression in step.Expressions)
            {
                var element = dm.Slect(expression);

                Rectangle rectangle = dm.CalculateElementRectangle(element);

                var top = accessor.ScrollTop;

                if (rectangle.Bottom - top > context.ClientRectangle.Bottom)
                {
                    accessor.ScrollTop = rectangle.Top - 10;
                    Application.DoEvents();
                    top = accessor.ScrollTop;
                }

                var bm = new Bitmap(rectangle.Width + 20, rectangle.Height + 20);

                Graphics g = Graphics.FromImage(bm);

                g.CopyFromScreen(context.PointToScreen(new Point(rectangle.X, rectangle.Y - 10 - top)), new Point(0, 0), new Size(bm.Width, bm.Height));

                g.Flush();

                g.Dispose();

                bitmaps.Add(bm);
            }

            var imageName = ReportApplication.MapPath(string.Format("Photo\\{0}-Step-{1}.jpg", context.ImageSetting.Name, step.Name));

            BitmapOperator.Combine(bitmaps).Save(imageName);

            return imageName;
        }
    }
}
